package com.blb.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.blb.dao.BaseDao;
import com.blb.utils.JDBCUtilsPlus;
import com.mysql.jdbc.ResultSetMetaData;

public class BaseDaoImpl implements BaseDao {

	/**
	 * 执行非查询语句
	 */
	@Override
	public void execute(String sql, Object... params) throws SQLException {
		Connection connection = JDBCUtilsPlus.getConnection();
		PreparedStatement prepareStatement = connection.prepareStatement(sql);
		for (int i=0; i<params.length; i++) {
			prepareStatement.setObject(i+1, params[i]);
		}
		System.out.println(prepareStatement.toString());
		prepareStatement.execute();
		JDBCUtilsPlus.colseResource(connection, prepareStatement, null);
	}

	/**
	 * 查询语句
	 */
	@Override
	public List<Map<String, Object>> get(String sql, Object... params)throws SQLException {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		Connection connection = JDBCUtilsPlus.getConnection();
		PreparedStatement prepareStatement = connection.prepareStatement(sql);
		for (int i=0; i<params.length; i++) {
			prepareStatement.setObject(i+1, params[i]);
		}
		System.out.println(prepareStatement.toString());
		ResultSet resultSet = prepareStatement.executeQuery();
		ResultSetMetaData resultSetMetaData = (ResultSetMetaData) resultSet.getMetaData();
		while (resultSet.next()) {
			Map<String, Object> map = new HashMap<String, Object>();
			for (int i=0; i<resultSetMetaData.getColumnCount(); i++) {
				String label = resultSetMetaData.getColumnLabel(i+1);
				map.put(label, resultSet.getObject(label));
			}
			list.add(map);
		}
		JDBCUtilsPlus.colseResource(connection, prepareStatement, null);
		return list;
	}
	
}
